package controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import interceptor.CategoryNavbarInterceptor;
import model.Category;
import model.Topic;

import java.util.List;

/**
 * Created by Administrator on 2018/5/11 0011.
 */
public class CategoryController extends Controller {
    public void list() {
        List<Category> categories = Category.dao.find("SELECT * FROM t_category");
        setAttr("categories", categories);
        renderFreeMarker("list.ftl");
    }


    public void add() {
        renderFreeMarker("add.ftl");
    }

    public void save() {
        String name = getPara("name");
        Category category = new Category();
        category.setName(name);
        boolean success = false; //添加成功的标志变量
        try {
            category.save();
            success = true;
        } catch (Exception e) {
            LogKit.error("版块添加失败，原因：" + e.getMessage());
        }
        String message = success ? "版块添加成功" : "版块添加失败";
        renderHtml(message + "<br><a href='/category/list'>返回版块列表</a>");
    }

    public void modify() {
        Integer id = getParaToInt(0, -1);
        Category category = Category.dao.findById(id);
        if (category != null) {
            setAttr("category", category);
            renderFreeMarker("modify.ftl");
        } else {
            renderHtml("<h3>指定的版块不存在!</h3>");
        }

    }

    public void update() {
        String name = getPara("name");
        Integer id = getParaToInt("id", -1);

        boolean success = false; //更新成功的标志变量
        try {
            Db.update("UPDATE t_category SET name = ? WHERE id = ?", name, id);
            success = true;
        } catch (Exception e) {
            LogKit.error("版块更新失败，原因：" + e.getMessage());
        }
        String message = success ? "版块更新成功" : "版块更新失败";
        renderHtml(message + "<br><a href='/category/list'>返回版块列表</a>");
    }

    public void delete() {
        // Integer id = getParaToInt("id", -1);
        Integer id = getParaToInt(0, -1);
        boolean success = false; //删除成功的标志变量
        try {
            Category.dao.deleteById(id);
            success = true;
        } catch (Exception e) {
            LogKit.error("版块删除失败，原因：" + e.getMessage());
        }
        String message = success ? "版块删除成功" : "版块删除失败";
        renderHtml(message + "<br><a href='/category/list'>返回版块列表</a>");
    }

    @Before(CategoryNavbarInterceptor.class)
    public void index() {
        Integer categoryId = getParaToInt(0, -1);
        Integer pageNumber = getParaToInt("page", 1);

        SqlPara sqlPara = Db.getSqlPara("getTopicsByCategory");
        sqlPara.addPara(categoryId);

        Page<Topic> topicPage = Topic.dao.paginate(pageNumber, 15, sqlPara);
        setAttr("topicPage", topicPage);
        renderFreeMarker("topic-list.ftl");
    }



}
